<template>
    <div class="goods-info">
        <h3>商品信息</h3>
        <div class="btn-box">
            <Button type="primary" @click="newItem" :disabled="disabled" size="small">新增</Button>
            <Button type="primary" @click="saveHandle" :disabled="disabled" size="small">保存</Button>
            <Button type="primary" @click="cancelHandle" :disabled="disabled" size="small">取消</Button>
            <Button type="primary" @click="removeItem" :disabled="disabled" size="small">删除</Button>
        </div>
        <div class="data-box form-mini">
            <table class="data-table" cellpadding="0" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th width="10%">序号</th>
                        <th width="15%">简要描述</th>
                        <th width="10%">件数</th>
                        <th width="15%">毛重（KG）</th>
                        <th width="20%">包装种类</th>
                        <th width="15%">危险品编号</th>
                        <th width="15%">描述补充</th>
                    </tr>
                </thead>
                <tbody>
                    <tr
                        v-for="(item, index) in goodsList"
                        :key="index"
                        @dblclick="dblclickHandle(item)"
                        @click="selectItem(index)"
                        :class="{'current-row' : currentIndex === index}"
                    >
                        <td width="10%">  <!--序号-->
                            <span style="display: inline-block; width: 20px;">{{ index + 1 }}</span>
                        </td>
                        <td width="15%">  <!--简要描述-->
                            <p v-if="!item.editStatus">{{ item.cargoBriefDesc }}</p>
                            <Input class="desc" v-model="item.cargoBriefDesc" v-if="item.editStatus" size="small" @keyup.native="setAssignFocus('quantity')"/>
                        </td>
                        <td width="10%">  <!--件数-->
                            <p v-if="!item.editStatus">{{ item.quantity }}</p>
                            <Input class="quantity" v-model="item.quantity" v-if="item.editStatus" size="small" @keyup.native="setAssignFocus('grossMeasure')"/>
                        </td>
                        <td width="15%">  <!--毛重（KG）-->
                            <p v-if="!item.editStatus">{{ item.grossMeasure }}</p>
                            <Input class="grossMeasure" v-model="item.grossMeasure" v-if="item.editStatus" size="small" @keyup.native="setAssignFocus('cargoPackingTypeName')"/>
                        </td>
                        <td width="20%">  <!--包装种类-->
                            <p v-if="!item.editStatus">{{ item.cargoPackingTypeName }}</p>
                            <Select
                                v-if="item.editStatus"
                                v-model="item.cargoPackingTypeName"
                                class="cargoPackingTypeName"
                                clearable
                                filterable
                                size="small"
                                :transfer="true"
                                @keyup.native="setAssignFocus('dangeriousCode')"
                                @on-query-change="(query) => queryChange(query, 'PACKING_TYPE', 2, goodsList, index, 'cargoPackingTypeName')"
                                @keyup.13.native="enterHandle(goodsList, index, 'cargoPackingTypeName', 'dataName')"
                            >
                                <Option
                                    v-for="(option, index) in mPackingTypeList"
                                    :key="index"
                                    :value="option.dataName"
                                    :label="option.dataName"
                                >{{option.dataCode+'/'+option.dataName}}</Option>
                            </Select>
                        </td>
                        <td width="15%">  <!--危险品编号-->
                            <p v-if="!item.editStatus">{{ item.dangeriousCode }}</p>
                            <Input class="dangeriousCode" v-model="item.dangeriousCode" v-if="item.editStatus" size="small" @keyup.native="setAssignFocus('cargoDesc')"/>
                        </td>
                        <td width="15%">  <!--描述补充-->
                            <p v-if="!item.editStatus">{{ item.cargoDesc }}</p>
                            <Input class="cargoDesc" v-model="item.cargoDesc" v-if="item.editStatus" size="small" @on-enter="cargoDescEnter"/>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script>
import { httpPost } from '@/libs/http'
import $ from 'jquery'

export default {
    name: 'GoodsInfo',
    props: ['mPackingTypeList', 'parentParams', 'disabled'],
    data () {
        return {
            goodsList: [],
            prevList: [],
            currentIndex: '',

            keyWord: '',
            dataMainType: '',
            searchType: ''
        }
    },

    watch: {
        'parentParams' (n, o) {
            this.goodsList = []
            this.currentIndex = ''
            if (JSON.stringify(n) === '{}' || !('consignmentCargoVos' in n.data)) { // 如果是手动新增 return false
                return false
            }
            let list = n.data.consignmentCargoVos // 如果是编辑初始赋值
            if (list.length > 0) {
                list.forEach(item => {
                    let obj = {
                        cargoBriefDesc: item.cargoBriefDesc,
                        quantity: item.quantity,
                        grossMeasure: item.grossMeasure,
                        cargoPackingTypeName: item.cargoPackingTypeName,
                        dangeriousCode: item.dangeriousCode,
                        cargoDesc: item.cargoDesc,
                        editStatus: false
                    }
                    this.goodsList.push(obj)
                })
            }
            this.prevList = JSON.parse(JSON.stringify(this.goodsList))
            // console.log(this.goodsList);
        }
    },

    methods: {
        newItem () {
            if (JSON.stringify(this.parentParams) !== '{}') {
                let obj = {
                    cargoBriefDesc: '',
                    quantity: '',
                    grossMeasure: '',
                    cargoPackingTypeName: '',
                    dangeriousCode: '',
                    cargoDesc: '',
                    editStatus: true
                }
                this.goodsList.push(obj)
                this.$nextTick(() => {
                    $('.goods-info .desc .ivu-input').focus()
                })
            } else {
                this.$Message.warning('请先选择提运单')
                return false
            }
        },

        dblclickHandle (item) {
            if (this.disabled) {
                return false
            }
            item.editStatus = !item.editStatus
        },

        selectItem (index) {
            this.currentIndex = index
        },

        removeItem () {
            if (!this.currentIndex.toString()) {
                this.$Message.warning('请单击选择需要删除的行')
                return false
            }
            if (this.goodsList.length === 0) {
                this.$Message.warning('已经没有删除的数据了')
                return false
            }
            this.goodsList.splice(this.currentIndex, 1)
        },

        cancelHandle () {
            this.currentIndex = ''
            this.goodsList = JSON.parse(JSON.stringify(this.prevList))
        },

        saveHandle () {
            let list = this.goodsList
            let mPackingTypeList = this.mPackingTypeList
            if (list.length === 0) {
                this.$Message.warning('没有需要保存的数据')
                return false
            }

            this.prevList = JSON.parse(JSON.stringify(this.goodsList))

            for (let i = 0; i < list.length; i++) {
                list[i].editStatus = false
                for (let j = 0; j < mPackingTypeList.length; j++) {
                    if (list[i].cargoPackingTypeName === mPackingTypeList[j].dataName) {
                        list[i].cargoPackingType = mPackingTypeList[j].dataCode
                    }
                }
            }
            let res = {
                index: this.parentParams.index,
                list: list
            }
            this.$emit('saveGoodsInfo', res)
            this.$Message.success('保存成功')
        },

        // Select 搜索关键词改变
        queryChange (query, dataMainType, searchType, list, index, attr) {
            if (query === '') {
                list[index][attr] = ''
                this.keyWord = ''
                return false
            }
            this.keyWord = query || ''
            this.dataMainType = dataMainType || ''
            this.searchType = searchType || ''
        },

        // Select 回车事件
        enterHandle (list, index, attr, field) {
            if (!this.keyWord) {
                return false
            }
            let declareUrl = '/ui/commonbasicdata/basicData/getBasicDataBeanByMinType'
            let manifestUrl = '/customs/manifestBasicData/list'
            let url = '' // type: 1-报关单基础数据字典接口  2-舱单基础数据字典接口
            if (this.searchType === 1) {
                url = declareUrl
            } else if (this.searchType === 2) {
                url = manifestUrl
            }

            let data = {
                dataMainType: this.dataMainType,
                pageNum: 1,
                pageSize: 10000,
                keyWord: this.keyWord
            }
            httpPost(url, data).then(res => {
                if (res.isSuccess) {
                    let resList = res.data
                    if (resList.length > 0) {
                        list[index][attr] = resList[0][field]
                    } else {
                        list[index][attr] = ''
                    }
                }
            })
            this.keyWord = ''
            this.dataMainType = ''
            this.searchType = ''
        },

        // 设置指定的元素获得焦点
        setAssignFocus (className) {
            let event = window.event || arguments[0]
            if (event.keyCode === 13) {
                let ele = document.getElementsByClassName(className)[0]
                let t = $(ele).find('.ivu-select-input')

                if (t.length) {
                    t.focus()
                } else {
                    $(ele).find('.ivu-input').focus()
                }
            }
        },

        cargoDescEnter () {
            setTimeout(() => {
                this.saveHandle()
            }, 300)
            $('.cargoDesc').find('.ivu-input').blur()
        }

    } // methods end
}

</script>

<style lang="less" scoped>

</style>
